
import React, { Component, createRef } from 'react'
import { DownOutlined, PlusOutlined, ExclamationCircleOutlined, FormOutlined } from '@ant-design/icons';
import { Button, Space, Dropdown, Menu, message, Modal, Input } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import MotionLayout from '@/layouts/MotionLayout';
import moment from "moment"
import { GuestbookList, GuestbookEdit, GuestbookDel } from "@/services/Guestbook";
import UpdateForm from './components/UpdateForm';
import {
  DeleteOutlined,
} from '@ant-design/icons';

const actionRef = createRef();

class Page extends Component {
  constructor(props) {
    super(props)
    this.state = {
      createModalVisible: false,
      updateModalVisible: false,
      selectRow: {},
    }
  }

  async handleDeal({ fields, serviceMethod, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const res = await serviceMethod(fields);
      hide();
      if (!res.success) {
        message.error(`${type}失败，${res.result}`);
        return false;
      }
      message.success(`${type}成功`);
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }
  async getDataSource(params) {
    const { result, success } = await GuestbookList({
      ...params,
      page: params.current,
      limit: params.pageSize,
    })
    if (!success) {
      return {
        data: [],
        page: 1,
        success: false,
        total: 0,
      };
    }
    return {
      data: result.arr,
      page: 1,
      success: true,
      total: result.count,
    };
  }
  createColumns() {
    return [
      {
        title: '昵称',
        dataIndex: 'nickName',
        formItemProps: { disabled: true }
      },
      {
        title: '留言',
        dataIndex: 'message',
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<Input.TextArea rows={3} disabled={true} />)
        },
        width: 300,
        hideInSearch: true,
      },
      {
        title: '回复人',
        dataIndex: 'replyName',
        hideInSearch: true,
      },
      {
        title: '回复内容',
        dataIndex: 'replyMessage',
        hideInSearch: true,
        hideInTable: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: 'dateTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm"),
        hideInSearch: true,
        hideInForm: true,
      },
      {
        title: '审核时间',
        dataIndex: 'updateTime',
        valueType: 'dateTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm"),
        hideInSearch: true,
        hideInForm: true,
      },
      {
        title: '显示顺序',
        dataIndex: 'orderNum',
        formItemProps: {
          type: "number"
        },
        rules: [{
          required: true,
        }],
      },
      {
        title: '是否上墙',
        dataIndex: 'isEnable',
        valueEnum: {
          [false]: {
            text: '否',
            status: 'Default',
          },
          [true]: {
            text: '是',
            status: 'Success',
          },
        },
      },
      {
        title: '操作',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, row) => (
          <Space>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                const selectRow = {
                  ...row,
                  orderNum: row.orderNum.toString(),
                  isEnable: row.isEnable.toString(),
                }
                this.setState({
                  updateModalVisible: true,
                  selectRow,
                })
              }}
              size="small" type="primary" icon={<FormOutlined />} ></Button>
            <Button
              onClick={(e) => {
                e.stopPropagation();
                Modal.confirm({
                  title: '是否确认删除?',
                  icon: <ExclamationCircleOutlined />,
                  onOk: async () => {
                    const idList = {
                      "id": [
                        row.id
                      ]
                    };
                    const success = await this.handleDeal({
                      type: "删除",
                      fields: idList,
                      serviceMethod: GuestbookDel,
                    });
                    if (!success) {
                      return;
                    }
                    if (!actionRef.current) {
                      return;
                    }
                    actionRef.current.reload();
                  },
                });
              }}
              size="small" type="primary" icon={<DeleteOutlined />}></Button>
          </Space>
        ),
      },
    ];
  }

  render() {


    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <ProTable
            actionRef={actionRef}
            headerTitle={""}
            rowKey="id"
            params={{}}
            request={async (params) => this.getDataSource(params)}
            columns={this.createColumns()}
            rowSelection={{}}
            search={false}
            pagination={{
              pageSize: 10,
            }}
            toolBarRender={(action, { selectedRowKeys, selectedRows }) => {

              return ([
                selectedRowKeys && selectedRowKeys.length > 0 && (
                  <Dropdown
                    overlay={
                      <Menu
                        onClick={async e => {
                          if (e.key === 'remove') {
                            const idList = {
                              "id": selectedRowKeys
                            };
                            Modal.confirm({
                              title: '是否确认删除?',
                              icon: <ExclamationCircleOutlined />,
                              onOk: async () => {
                                const success = await this.handleDeal({
                                  type: "删除",
                                  fields: idList,
                                  serviceMethod: GuestbookDel
                                });
                                if (!success) {
                                  return;
                                }
                                if (!actionRef.current) {
                                  return;
                                }
                                actionRef.current.reload();
                              },
                            });
                          }
                        }}
                        selectedKeys={[]}
                      >
                        <Menu.Item key="remove">批量删除</Menu.Item>
                        <Menu.Item key="approval">批量审批</Menu.Item>
                      </Menu>
                    }
                  >
                    <Button>
                      批量操作 <DownOutlined />
                    </Button>
                  </Dropdown>
                ),
              ]);
            }}
          />
        </MotionLayout>
        <UpdateForm
          onCancel={() => this.setState({ updateModalVisible: false })}
          updateModalVisible={this.state.updateModalVisible}
        >
          <ProTable
            onSubmit={async fieldsValues => {
              const fields = {
                ...fieldsValues,
                orderNum: Number(fieldsValues.orderNum),
                isEnable: fieldsValues.isEnable == "true",
                id: this.state.selectRow.id,
              }
              const success = await this.handleDeal({
                type: "更新",
                fields,
                serviceMethod: GuestbookEdit,
              });
              if (!success) {
                return;
              }
              this.setState({
                updateModalVisible: false,
              })
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            rowKey="id"
            type="form"
            form={{
              initialValues: {
                ...this.state.selectRow,
              }
            }}
            columns={this.createColumns()}
            rowSelection={{}}
          />
        </UpdateForm>
      </PageHeaderWrapper>
    )
  }
}
export default Page
